
class RecoderWorkletProcessor extends AudioWorkletProcessor {
    constructor(options) {
        super(options);
        this.port.onmessage = this.onMessage.bind(this);
        this.closing = false;
        this.isStarted = false;
        this.sampleRate = 16000;
        this.frameCount = Math.ceil(this.sampleRate / 50);
        this.inputBuffer = undefined;
        this.inputBufferOffset = 0;
        console.log("constructor")
    }

    onMessage(event) {
        const evt = event.data.event;
        if (evt === "REC_START") {
            this.isStarted = true;
            console.log("change to ", this.isStarted);
        }else if (evt === "REC_STOP") {
            this.isStarted = false;
        }else if (evt === "REC_CLOSE") {
            this.inputBuffer = null;
            this.closing = true;
        }else if (evt === "REC_OPEN") {
            this.inputBufferOffset = 0;
            this.sampleRate = event.data.data.sampleRate;
            this.frameCount = Math.ceil(this.sampleRate / 50);
            this.inputBuffer = new Float32Array(this.frameCount * 1000);
            this.port.postMessage({
                open: true
            });
        }
    }

    process(inputs, outputs, params) {
        let input = (inputs[0] || [])[0] || [];

        if (!this.isStarted) {
            return true;
        }

        if (input.length) {
            this.inputBuffer.set(input, this.inputBufferOffset);
            this.inputBufferOffset += input.length;


            if (this.inputBufferOffset >= this.frameCount) {
                this.port.postMessage({
                    data: this.inputBuffer.slice(0, this.frameCount)
                });
                this.inputBuffer.copyWithin(0, this.frameCount, this.inputBufferOffset)
                this.inputBufferOffset -= this.frameCount;
            }
        }

        return !this.closing;
    }
}

registerProcessor('worklet_recorder', RecoderWorkletProcessor);
